package com.example.forum2.Service.impl;

import com.example.forum2.Service.IUserService;
import com.example.forum2.comment.AppResult;
import com.example.forum2.comment.ResultCode;
import com.example.forum2.dao.BoardMapper;
import com.example.forum2.dao.UserMapper;
import com.example.forum2.exception.ApplicationExeception;
import com.example.forum2.model.Board;
import com.example.forum2.model.User;
import com.example.forum2.utils.MD5Util;
import com.example.forum2.utils.StringUtil;
import com.example.forum2.utils.UUIDUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BoardMapper boardMapper;

    @Override
    public void CreateNomalUser(User user) {
        if(user==null){
            throw  new ApplicationExeception(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        if(userMapper.selectByUserName(user.getUsername())!=null){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        user.setGender((byte) 2);
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if(row!=1){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));
        }
        log.info("新增用户成功");
    }

    @Override
    public User selectByUserName(String username) {
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
            throw  new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User user = selectByUserName(username);
        if(user==null){
            throw  new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
       if(!encryptPassword.equals(user.getPassword())){
             throw  new ApplicationExeception(AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME ));
       }
      return user;
    }

    @Override
    public User selectById(Long Id) {
       return userMapper.selectByPrimaryKey(Id);
    }

    @Override
    public List<Board> selectAllNormal() {
          return boardMapper.selectAllNormal();
    }

    @Override
    public List<Board> selectByNum(Integer num) {
        if(num<=0){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));
        }
        return boardMapper.selectByNum(num);
    }

    @Override
    public void addOneArticleCountById(Long id) {
          if(id==null||id<=0){
              throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));
          }
          User user= userMapper.selectByPrimaryKey(id);
          if(user==null){
              throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
          }
          User user1 = new User();
         user1.setId(user.getId());
         user1.setArticleCount(user.getArticleCount()+1);
         int row = userMapper.updateByPrimaryKeySelective(user1);
         if(row!=1){
             throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_CREATE));
         }
    }

    @Override
    public void subOneArtucleCountById(Long id) {
    if(id==null||id<=0||id<=0){
        throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_BANNED));
    }
    User user = userMapper.selectByPrimaryKey(id);
    if(user==null){
        throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));
    }
    User updateUser = new User();
    updateUser.setId(user.getId());
    updateUser.setArticleCount(user.getArticleCount()-1);
    if(updateUser.getArticleCount()<0){
        updateUser.setArticleCount(0);
    }
    int row = userMapper.updateByPrimaryKeySelective(updateUser);
    if(row!=1){
        throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));
    }
    }




    @Override
    public void modifyInfo(User user) {
        if(user==null||user.getId()==null||user.getId()<=0){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser==null){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        boolean checkAtr = false;
        User updateUser = new User();
        updateUser.setId(user.getId());
        if(!StringUtil.isEmpty(user.getUsername())&&!existsUser.getUsername().equals(user.getUsername())){
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser!=null){
                throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_BANNED));
            }
            updateUser.setUsername(user.getUsername());
            checkAtr=true;
        }
       if(!StringUtil.isEmpty(user.getNickname())&&!existsUser.getNickname().equals(user.getNickname())){
           updateUser.setNickname(user.getNickname());
           checkAtr=true;
       }
       if(user.getGender()!=null&&existsUser.getGender()!=user.getGender()){
           updateUser.setGender(user.getGender());
           if(updateUser.getGender()>2||updateUser.getGender()<0){
               updateUser.setGender((byte)2);
           }
           checkAtr=true;
       }
       existsUser.setEmail("a");
       if(!StringUtil.isEmpty(user.getEmail())&&!existsUser.getEmail().equals(user.getEmail())){
           updateUser.setEmail(user.getEmail());
           checkAtr=true;
       }

        if (!StringUtil.isEmpty(user.getPhoneNum())

                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {

            updateUser.setPhoneNum(user.getPhoneNum());
            checkAtr = true;

        }else{
            updateUser.setPhoneNum(user.getPhoneNum());
        }
        if (!StringUtil.isEmpty(user.getRemark())

                && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkAtr = true;

        }
        if (checkAtr == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);

        if (row != 1) {

            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");

            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));

        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if(id==null||id<=0||StringUtil.isEmpty(newPassword)||StringUtil.isEmpty(oldPassword)){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null||user.getDeleteState()==1){
            throw  new ApplicationExeception(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String OldEncyptPassword=MD5Util.md5Salt(oldPassword,user.getSalt());
        if(user.getPassword().equals(OldEncyptPassword)){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));
        }
        String salt = UUIDUtil.UUID_32();
        String encryPassword = MD5Util.md5Salt(newPassword,salt);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryPassword);
        int row =userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            throw new ApplicationExeception(AppResult.failed(ResultCode.FAILED));
        }
    }
}
